package com.hehao.java_basic.design_mode.creational.singleton;

import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class SingletonDemo {
    //懒汉式
    private static volatile SingletonDemo lazyInstance;

    //饿汉式
    private static final SingletonDemo eagerInstance = new SingletonDemo();

    //私有化构造方法，只能通过静态方法获取
    private SingletonDemo() {
    }
    //懒汉式获取方法
    public static SingletonDemo getLazyInstance() {
        //双重检查锁定（Double-Checked Locking）
        if (null==lazyInstance) {
            synchronized (SingletonDemo.class) {
                if (null==lazyInstance) {
                    lazyInstance = new SingletonDemo();
                }
            }
        }
        return lazyInstance;
    }

    //饿汉式获取方法
    public static SingletonDemo getEagerInstance() {
        return eagerInstance;
    }

    public static void main(String[] args) {
        // 并发线程数
        int threadCount = 1000;
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        for (int i = 0; i < threadCount; i++) {
            executorService.execute(() -> {
                SingletonDemo lazySingleton = SingletonDemo.getLazyInstance();
                SingletonDemo eagerSingleton = SingletonDemo.getEagerInstance();
                System.out.println(lazySingleton);
                System.out.println(eagerSingleton);
            });
        }
        executorService.shutdown();
    }
}